package com.scau.yangsuiyu.estore.service;

import com.scau.yangsuiyu.estore.dababases.dao.CartDao;
import com.scau.yangsuiyu.estore.dababases.dao.ItemDao;
import com.scau.yangsuiyu.estore.dababases.entity.Buyer;
import com.scau.yangsuiyu.estore.dababases.entity.Cart;
import com.scau.yangsuiyu.estore.dababases.entity.Goods;
import com.scau.yangsuiyu.estore.dababases.entity.Item;

import java.util.ArrayList;
import java.util.List;

/**
 * @author suiyu_yang
 * @description 购物车的逻辑业务
 * @date 2019-06-21 15:02
 * @email suiyu_yang@163.com
 */
public class CartService {

    public void addToCart(Buyer buyer, Item item) {
        Item tempItem = findSameItemOfCart(buyer, item);
        Cart cart = new Cart();
        cart.setBuyerId(buyer.getId());
        if (tempItem == null) { //找不到，插入
            tempItem = item;
            new ItemDao().insert(tempItem);
            cart.setItemId(tempItem.getId());
            new CartDao().insert(cart);
        } else {  //找得到，更新数量
            int oldAmount = tempItem.getAmount();
            int newAmount = oldAmount + item.getAmount();

            tempItem.setAmount(newAmount);
            tempItem.setPaymentPrice(tempItem.getGoods().getPromotionPrice() * newAmount);
            tempItem.setTotalPrice(tempItem.getGoods().getPrice() * newAmount);

            new ItemDao().update(tempItem);
            new CartDao().update(cart);
        }


    }

    /**
     * 获取用户购物车中的所有商品项
     *
     * @param buyer
     * @return
     */
    public List<Item> getAllItemOfCart(Buyer buyer) {
        List<Item> items = new ArrayList<>();
        List<Cart> carts = new CartDao().getCartByBuyer(buyer);

        for (Cart cart : carts) {
            items.add(new ItemDao().getItemByItemId(cart.getItemId()));
        }

        return items;
    }

    private Item findSameItemOfCart(Buyer buyer, Item javaItem) {
        Goods goods = javaItem.getGoods();

        for (Item dbItem : getAllItemOfCart(buyer)) {
            if (dbItem.getGoods().getId() == goods.getId()) {
                return dbItem;
            }
        }
        return null;
    }
}
